<?php
/**
 * 个人中心
 * Created by PhpStorm.
 * User: sk
 * Date: 2018/5/29
 * Time: 10:53
 */

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Auth;
use App\Helpers\ReturnMessage;

//use Illuminate\Support\Facades\Request;


class PersonalController extends BaseController
{
    /**
     * [个人中心接口]
     * @Author sk
     * @DateTime 2018-05-29
     * @version  0.8
     * @param Request $request
     * @return array
     */
    public function sidebar()
    {
        $arr = (JWTAuth::parseToken()->authenticate());
        if ($arr) {
            $data = json_decode($arr, true);
            $user['phone'] = $data['phone'];
            $user['picture'] = $data['picture'];
            $user['sex'] = (string)$data['sex'];
            $user['nickname'] = $data['nickname'];
            $user = json_decode(json_encode($user), true);
            return response(['user' => $user, 'code' => '1000', 'message' => '获取数据成功！'], 200);
        } else {
            return response(['code' => '1001', 'message' => '请求要求身份验证，未查询到用户信息！'], 401);
        }
    }

    /**
     * 个人中心--上传头像
     * @param Request $request
     * @return \App\Helpers\json|\Illuminate\Http\JsonResponse
     */
    public function uploadPhoto(Request $request)
    {
        try {
            $arr = (JWTAuth::parseToken()->authenticate());
            $data = json_decode($arr, true);
            $id = $data['id'];
            $file = $request->file('picture');
            //return $file;
            if ($file) {
                $file_path = 'uploads/' . date("Ym") . "/";
                $extension = $file->getClientOriginalExtension();//上传文件的后缀.
                $file_name = md5(time() . mt_rand(10, 99)) . '.' . $extension;
                $info = $file->move($file_path, $file_name);
                // return $info;
                if (!$info) {
                    $error = $file->getError();
                    return response(['msg' => $error, 'code' => '1011', 'message' => '图片保存到本地失败']);
                }
                $data['picture'] = $file_path . $file_name;
                // dd($data['picture']);
                $re = DB::table('social_user')->where('id', $id)->update(['picture' => $data['picture']]);

                if ($re) {
                    $fromData = [
                        'code' => '1000',
                        'data' => $data['picture'],
                        'sex' => (string)$data['sex'],
                        'nickname' => $data['nickname'],
                        'phone' => $data['phone'],
                    ];
                    $data = json_decode(json_encode($fromData), true);
                    return response(['msg' => $data, 'code' => '1000', 'message' => '图片上传成功']);
                } else {
                    return response(['msg' => '', 'code' => '1011', 'message' => '图片保存到数据库失败']);
                }
            } else {
                return response(['msg' => '', 'code' => '1011', 'message' => '获取图片失败']);
            }
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => '1007', 'message' => '非法token']);
        }
    }


    /**
     * [编辑资料接口]
     * @Author sk
     * @DateTime 2018-05-29
     * @version  0.8
     * @param Request $request
     * @return array
     */
    public function edit(Request $request)
    {
        $arr = (JWTAuth::parseToken()->authenticate());
        $array = json_decode($arr, true);
        $data = $request->all();
        $userdata['nickname'] = $array['nickname'];
        $userdata['phone'] = $array['phone'];
        $userdata['sex'] = $array['sex'];
        $userdata['update_at'] = time();
        if (!empty($data['nickname']) && !empty($data['phone']) && !empty($data['sex'])) {
            $uid = $array['id'] ? $array['id'] : '';
            $re = Db:: table('social_user')->where('id', $uid)->update([
                'nickname' => $data['nickname'],
                'phone' => $data['phone'],
                'sex' => $data['sex'],
                'update_at' => time(),
            ]);
            $getdatas = Db:: table('social_user')->where('id', $uid)->first();
            $getdata = get_object_vars($getdatas);
            $datas['nickname'] = $getdata['nickname'];
            $datas['phone'] = $getdata['phone'];
            $datas['sex'] = (string)$getdata['sex'];
            $user = json_decode(json_encode($datas), true);
            // dd($user);
            if ($re) {
                return response(['user' => $user, 'code' => '1000', 'message' => '操作成功！'], 200);
            }
        } else {
            return response(['code' => '1011', 'message' => '操作失败，请确认参数填写完整！'], 400);
        }
    }

    /**
     * 【法律条款与政策】
     * @Author sk
     * @DateTime 2018-05-31
     * @version  0.8
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function terms(Request $request)
    {
        $arr = (JWTAuth::parseToken()->authenticate());
        // $data = json_decode($arr, true);
        return $arr ? response(['url' => 'Personal/terms', 'code' => '1000', 'message' => '操作成功！'], 200) : response(['msg' => '', 'code' => '1007', 'message' => '非法token']);
    }

    /**
     * 【关于时代出行】
     * @Author sk
     * @DateTime 2018-05-31
     * @version  0.8
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function about(Request $request)
    {
        $arr = (JWTAuth::parseToken()->authenticate());
        return $arr ? response(['url' => 'Personal/about', 'code' => '1000', 'message' => '操作成功！'], 200) : response(['msg' => '', 'code' => '1007', 'message' => '非法token']);
    }

    /**
     * 【消息通知】
     * @Author sk
     * @DateTime 2018-05-31
     * @version  0.8
     * @param Request $request
     * @return array
     */
    public function push(Request $request)
    {
        $arr = (JWTAuth::parseToken()->authenticate());
        $data = json_decode($arr, true);
        $pushdata['push'] = json_decode($request['push']);
        Db::table('social_user')->where('id', $data['id'])->update($pushdata);
        $datapush = Db::table('social_user')->where('id', $data['id'])->first();
        $array = get_object_vars($datapush);
        $arraypush['push'] = $array['push'];
        // $push = json_encode($arraypush);
        $push = json_decode(json_encode($arraypush), true);
        if ($push) {
            return response([
                'push' => $push, 'code' => '1000', 'message' => '操作成功！'], 200);
        } else {
            return ['code' => '1011', 'message' => '操作失败！'];
        }
    }

    /**
     * 【退出登录的方法】
     * @Author sk
     * @DateTime 2018-05-31
     * @version  0.8
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function logout(Request $request)
    {
        JWTAuth::invalidate();

        return response([
            'status' => 'success',
            'code' => '1000',
            'msg' => '退出成功.'
        ], 200);
    }

//【test】
    public function test()
    {
        $user = User::where('id', 64)->select('id')->first();
        return JWTAuth::fromUser($user);
    }

}